<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

class Busrecycle extends Backend
{
    protected $model = null;
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->model = model("Business.Business");
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->with(['source', 'admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->model
                ->onlyTrashed()
                ->with(['source', 'admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo $this->SubjectOrderModel->getlastSql();
            // exit;
            $result = array("total" => $total, "rows" => $list);
            // var_dump(collection($result)->toArray());
            // exit;
            return json($result);

        }
        return $this->view->fetch();
    }
    // 还原
    public function reduction($ids = null)
    {
        $id = empty($ids) ? [] : explode(',', $ids);
        $data = [];
        foreach ($id as $item) {
            $res = $this->model->onlyTrashed()->find($item);
            if (!$res) {
                $this->error('未找到当前客户');
                exit;
            }
            $list = ['id' => $item, 'deletetime' => null];
            array_push($data, $list);
        }

        // 批量还原
        $result = $this->model->isUpdate(true)->saveAll($data);
        if ($result) {
            $this->success('还原客户成功');
            exit;
        } else {
            $this->error($this->model->getError());
            exit;
        }
    }
    // 删除
    public function del($ids = null)
    {
        $id = empty($ids) ? [] : explode(',', $ids);
        $srclist=[];
        foreach ($id as $item) {
            $res = $this->model->onlyTrashed()->find($item);
            if (!$res) {
                $this->error('未找到当前客户');
                exit;
            }
            // 获取客户的图片地址
            array_push($srclist, $res['avatar_text']);
        }
        $srclist = array_filter($srclist);
     
        $result = $this->model->destroy($id, true);
        if ($result) {
            // 批量删除客户图片
            foreach ($srclist as $val) {
                // var_dump($val);
                @is_file('.' . $val) && @unlink('.' .$val);
                $path = pathinfo($val, PATHINFO_DIRNAME);
                @rmdir($path);//删除空目录
            }
            $this->success('删除客户成功');
            exit;
        } else {
            $this->error($this->model->getError());
            exit;
        }
    }
}